package com.onemile.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * ʹ�� GZip ѹ���ͽ�ѹ
 */
public class UtiGZip
{
	/**
	 * ѹ��
	 * 
	 * @param bytes
	 * @return
	 */
	public static byte[] compress(byte[] bytes)
	{
		
		if (bytes == null)
		{
			return null;
		}
		
		byte[] dst = null;
		try
		{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(out);
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			byte[] buff = new byte[in.available()];
			int length = 0;
			while ((length = in.read(buff)) > 0)
			{
				gzip.write(buff, 0, length);
			}
			dst = out.toByteArray();
			gzip.close();
			in.close();
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		return dst;
	}
	
	/**
	 * ��ѹ
	 * 
	 * @param bytes
	 * @return
	 */
	public static byte[] decompress(byte[] bytes)
	{
		
		if (bytes == null)
		{
			return null;
		}
		
		byte[] src = null;
		try
		{
			GZIPInputStream gin = new GZIPInputStream(new ByteArrayInputStream(bytes));
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int length = 0;
			while ((length = gin.read(buff, 0, buff.length)) > 0)
			{
				out.write(buff, 0, length);
			}
			src = out.toByteArray();
			gin.close();
			out.close();
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		return src;
	}
}
